<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="120px">
      <el-form-item label="讲师名称">
        <el-input v-model="teacher.name" />
      </el-form-item>
      <el-form-item label="入驻时间">
        <el-date-picker v-model="teacher.joinDate" value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item label="讲师排序">
        <el-input-number v-model="teacher.sort" :min="0" />
      </el-form-item>
      <el-form-item label="讲师头衔">
        <el-select v-model="teacher.level">
          <!--
            数据类型一定要和取出的json中的一致，否则没法回填
            因此，这里value使用动态绑定的值，保证其数据类型是number
            -->
          <el-option :value="1" label="高级讲师" />
          <el-option :value="2" label="首席讲师" />
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历">
        <el-input v-model="teacher.career" />
      </el-form-item>
      <el-form-item label="讲师简介">
        <el-input v-model="teacher.intro" :rows="10" type="textarea" />
      </el-form-item>

      <!-- 讲师头像-->
      <el-form-item label="讲师简介">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
          accept="image/jpeg,image/png"
          :action="BASE_API + '/admin/oss/upload?module=avatar'"
        >
          <img v-if="teacher.avatar" :src="teacher.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate()"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { save, getById, updateById } from "@/api/teacher";

export default {
  data() {
    return {
      teacher: {
        avatar: "",
        sort: 0,
        level: 1,
      },
      saveBtnDisabled: false, // 默认按钮可用
      BASE_API: process.env.VUE_APP_BASE_API,
    };
  },
  created() {
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id);
    }
  },
  methods: {
    saveOrUpdate() {
      this.$route.params.id ? this.updateData() : this.saveData();
    },
    //新增讲师
    saveData() {
      save(this.teacher).then((res) => {
        if (res.success) {
          // 弹出成功提示
          this.$message.success(res.message);
          this.saveBtnDisabled = true;
          this.$router.push({ path: "/teacher" });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 根据id查询讲师
    fetchDataById(id) {
      getById(id).then((response) => {
        this.teacher = response.data;
      });
    },
    //更新讲师
    updateData() {
      updateById(this.teacher).then((res) => {
        if (res.success) {
          // 弹出成功提示
          this.$message.success(res.message);
          this.saveBtnDisabled = true;
          this.$router.push({ path: "/teacher" });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //文件上传成功
    handleAvatarSuccess(response) {
      if (response.success) {
        this.teacher.avatar = response.data;
        //强制重新渲染
        //this.$forceUpdate();
      } else {
        this.$message.error(response.message);
      }
    },
    //文件上传失败（http）
    handleAvatarError() {
      this.$message.error("网络错误！上传失败");
    },
    //文件上传前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png"; // MIME格式
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传的头像图片只能是 JPG 或 PNG 格式！");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB！");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>